// pages/home-add/home-add.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    company_id: '',
    add_comp_logo: [], //官网logo
    add_banner_img: [], //banner
    add_about_img: [], //关于我们
    add_honour_img: [], //荣誉
    addressName: '',
    addressDetail: '',
    latitude: '',
    longitude: '',
  },

  addProduct: function () { //添加产品
    wx.navigateTo({
      url: '/pages/mine/my-product/my-product',
    })
  },

  openMap: function () { //打开地图选择位置
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success(re) {
              wx.chooseLocation({
                success: function (res) {
                  console.log(res)
                  that.setData({
                    addressName: res.name,
                    addressDetail: res.address,
                    latitude: res.latitude,
                    longitude: res.longitude
                  })
                },
                fail(res) {
                  console.log(res)
                }
              })
            },
            fail(re) {
              console.log(111111)
              console.log(re)
              that.getSetting();
            },
          })
        } else { //已授权
          wx.chooseLocation({
            success: function (res) {
              console.log(res)
              that.setData({
                addressName: res.name,
                addressDetail: res.address,
                latitude: res.latitude,
                longitude: res.longitude
              })
            },
            fail(res) {
              console.log(res)
            }
          })
        }
      }
    })

  },

  getSetting(e) { //获取权限设置
    let that = this;
    wx.getSetting({
      success: function (res) {
        console.log(res.authSetting)
        if (!res.authSetting['scope.userLocation']) {
          wx.showModal({
            title: '是否授权位置权限',
            content: '需要获取您的位置权限，请确认授权，否则无法调用地图',
            showCancel: true,
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '授权失败',
                  icon: 'success',
                  duration: 1000
                })
              } else { //确定
                wx.openSetting({
                  success(re) {
                    console.log(re.authSetting)
                    if (re.authSetting["scope.userLocation"]) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      that.openMap();
                    } else {
                      wx.showToast({
                        title: '授权失败!',
                        icon: 'success',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            },
            fail: function (res) {},
            complete: function (res) {},
          })
        } else { //已授权
          // that.openMap();
        }

      },
      fail: function (res) {},
      complete: function (res) {},
    })

  },

  //添加图片
  chooseIMG: function (e) {
    let that = this;
    let type = e.currentTarget.dataset.type;
    let {
      add_comp_logo,
      add_banner_img,
      add_about_img,
      add_honour_img
    } = that.data;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePaths可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;

        wx.uploadFile({
          url: app.globalData.host + 'common/uploadimg',
          filePath: tempFilePaths[0],
          name: 'file',
          success: function (res) {
            console.log(res)
            res = JSON.parse(res.data);
            // res = JSON.parse(res);
            if (type == '1') {
              add_banner_img.push(res.filesrc)
            } else if (type == '2') {
              add_about_img.push(res.filesrc)
            } else if (type == '3') {
              add_honour_img.push(res.filesrc)
            } else {
              add_comp_logo = [res.filesrc]
            }
            that.setData({
              add_comp_logo,
              add_banner_img,
              add_about_img,
              add_honour_img,
            })
          },
          fail: function (res) {},
          complete: function (res) {},
        })
        console.log(that.data.add_comp_img)
        console.log(that.data.add_banner_img)
        console.log(that.data.add_about_img)
        console.log(that.data.add_honour_img)
      },
    })
  },

  removePhoto: function (e) { //移除图片
    let that = this;
    let idx = e.currentTarget.dataset.idx
    let type = e.currentTarget.dataset.type
    let {
      add_comp_logo,
      add_banner_img,
      add_about_img,
      add_honour_img
    } = that.data;

    if (type == '1') {
      let list = add_banner_img;
      list.splice(idx, 1)
      that.setData({
        add_banner_img: list
      })
    } else if (type == '2') {
      let list = add_about_img;
      list.splice(idx, 1)
      that.setData({
        add_about_img: list
      })
    } else if (type == '3') {
      let list = add_honour_img;
      list.splice(idx, 1)
      that.setData({
        add_honour_img: list
      })
    } else {
      that.setData({
        add_comp_logo: []
      })
    }

  },

  inputDetailAddress: function (e) { //详细地址
    var that = this;
    var detailAddress = e.detail.value;
    that.setData({
      addressName: detailAddress
    })
  },

  submitTap: function (e) { //提交
    console.log(e)
    var that = this;
    var {
      add_comp_logo,
      add_banner_img,
      add_about_img,
      add_honour_img,
      addressName,
      addressDetail,
      latitude,
      longitude
    } = that.data;
    var formId = e.detail.formId;
    var {
      target,
      aboutText,
      awardText,
      phone
    } = e.detail.value;
    if (add_comp_logo.length == 0) {
      wx.showToast({
        title: '请上传公司logo',
        icon: 'none',
      })
      return;
    } else if (target.length == 0) {
      wx.showToast({
        title: '请添加业务关键字',
        icon: 'none',
      })
      return;
    }
    // else if (add_about_img.length == 0) {
    //   wx.showToast({
    //     title: '请添加关于我们图片',
    //     icon: 'none',
    //   })
    //   return;

    // } else if (aboutText.length == 0) {
    //   wx.showToast({
    //     title: '请填写关于我们描述',
    //     icon: 'none',
    //   })
    //   return;

    // }
    var content = {};
    content['add_comp_logo'] = add_comp_logo;
    content['add_banner_img'] = add_banner_img;
    content['add_about_img'] = add_about_img;
    content['add_honour_img'] = add_honour_img;
    content['target'] = target;
    content['aboutText'] = aboutText;
    content['awardText'] = awardText;
    content['phone'] = phone;
    content['addressName'] = addressName;
    content['addressDetail'] = addressDetail;
    content['latitude'] = latitude;
    content['longitude'] = longitude;
    console.log(content)

    app.getFormId(formId);
    wx.requestSubscribeMessage({
      tmplIds: ['rTy3RHLVn-uV4uNpZE2sl2ukLTpSkAWd6TcSxTwgGCs'],
      success(res) {
        let temid = 'rTy3RHLVn-uV4uNpZE2sl2ukLTpSkAWd6TcSxTwgGCs'
        var params = {
          content: JSON.stringify(content),
          user_id: wx.getStorageSync('userId'),
          company_id: that.data.company_id,
        };
        if (res[temid] == 'accept') {
          params.check = 1
          that.website(params)
        } else {
          params.check = 0
          that.website(params)
        }
      }
    })
  },
  website(params) {
    app.request(app.globalData.host + 'website/add', params, 'POST', true,
      function (res) {
        console.log(res)
        if (res.data.code == 1) {
          wx.showToast({
            title: '提交成功，等待审核',
            icon: 'none',
            duration: 1500,
          })

          // setTimeout(function() {
          //   wx.navigateBack({
          //     delta: 1,
          //   }, 1500)
          // })
        }
      },
      function (err) {},
      function (complete) {})
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getHomeMsg(); //获取官网信息
  },

  getHomeMsg() { //获取官网信息
    var that = this;
    wx.request({
      url: app.globalData.host + 'website/index',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: "GET",
      data: {
        user_id: wx.getStorageSync('userId')
      },
      success(res) {
        if (res.data.data.content != '') {
          var content = JSON.parse(res.data.data.content)
          that.setData({
            add_comp_logo: content.add_comp_logo,
            add_banner_img: content.add_banner_img,
            add_about_img: content.add_about_img,
            add_honour_img: content.add_honour_img,
            target: content.target,
            aboutText: content.aboutText,
            awardText: content.awardText,
            phone: content.phone,
            addressName: content.addressName,
            addressDetail: content.addressDetail,
            latitude: content.latitude,
            longitude: content.longitude,
            company_id: res.data.data.id,
          })
        }
      },
      fail(err) {},
      complete(comp) {},
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})